import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    // 购物车
    cart: []
  }

  methods = {
    // 更新选中状态
    updateCheckStatus(e) {
      const index = this.cart.findIndex(x => x.id === e.target.dataset.id)
      if (index !== -1) {
        this.cart[index].isCheck = e.detail
      }
      this.$parent.updateCart(this.cart)
    },
    // 更新商品数量
    updateCount(e) {
      const index = this.cart.findIndex(x => x.id === e.target.dataset.id)
      if (index !== -1) {
        this.cart[index].count = e.detail
      }
      this.$parent.updateCart(this.cart)
    },
    // 删除商品
    close(id) {
      this.$parent.removeGoodsById(id)
    },
    // 切换全选
    fullChecked() {
      let isFullChecked = this.isFullChecked
      this.cart.forEach(x => {
        x.isCheck = !isFullChecked
      })
      this.$parent.updateCart(this.cart)
    },
    // 提交订单
    async submitOrder() {
      wepy.navigateTo({ url: '/pages/order' });
      
    }
  }


  onLoad() {
    this.cart = this.$parent.globalData.cart
  }

  computed = {
    isEmpty() {
      if (this.cart.length <= 0) {
        return true
      }
      return false
    },
    // 计算总价格
    amount() {
      let price = 0
      this.cart.forEach(x => {
        if (x.isCheck)
          price += x.price
      })
      return price * 100
    },
    // 全选
    isFullChecked() {
      let num = 0
      this.cart.forEach(x => {
        if (x.isCheck)
          num++
      })
      if (num === this.cart.length) {
        return true
      }
      return false
    },
    // 禁用提交订单
    disableSubmit() {
      if (this.$parent.globalData.total === 0) {
        return true
      }
      return false
    }
  }
}